import Vue from "vue";
import Router from "vue-router";
import Layout from "@/views/layout/layout";
import store from '@/store/index';
Vue.use(Router);

// 无需登录的路由
const initRoutes = [
  {
    path: "/",
    redirect: "/login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue"),
  },
  {
    path: "/about",
    name: "about",
    component: () => import("../views/about/about.vue"),
  },
];


// 普通管理员路由 
export const adminRoutes = [
  {
    path: "/home",
    name: "home",
    meta: {
      title: "首页",
      icon: "location-o",
    },
    component: Layout,
    redirect: "/home/index",
    children: [
      {
        path: "index", // /home/index
        name: "home-inex",
        component: () => import("../views/home/home.vue"),
      },
      {
        path: "list", // /home/list
        name: "home-list",
        component: () => import("../views/home/list.vue"),
      },
    ],
  },
  {
    path: "/type",
    name: "type",
    meta: {
      title: "分类",
      icon: "like-o",
    },
    component: Layout,
    redirect: "/type/index",
    children: [
      {
        path: "index", // /type/index
        name: "type-inex",
        component: () => import("../views/type/type.vue"),
      },
    ],
  },
  {
    path: "/cart",
    name: "cart",
    meta: {
      title: "购物车",
      icon: "star-o",
    },
    component: Layout,
    redirect: "/cart/index",
    children: [
      {
        path: "index", // /cart/index
        name: "cart-inex",
        component: () => import("../views/cart/cart.vue"),
      },
    ],
  },
];

// 超级管理员路由
export const superRoutes = [
  // 超级管理也拥有普通管理员的路由
  ...adminRoutes,
  {
    path: '/account',
    component: Layout,
    meta: {
      title: "账号管理",
      icon: "location-o",
    },
    children:[
      {
        path: 'index',
        name: 'account-index',
        component: ()=>import('../views/account/account.vue')
      }
    ]
  }
]


const router = new Router({
  // 刚开始只配置无需登录的路由
  routes: initRoutes
});

/**
 * to 要去的路由
 * from 当前路由
 * next 执行下一步操作 next(), next('/login')
 */

/**
 * 判断逻辑:
 * 1. 判断是否应登录
 * 2. 判断要去哪个路由
 * 3. 设置一个白名单, 白名单上面的路由直接放行, 比如login
 */

let whiteList = ['login','about'];
router.beforeEach((to,from,next)=>{ 
  let token = store.state.token;
  // token存在表示已经登录
  if (token) {
    // 已登录, 所去路由为login时,直接跳首页
    if(to.name === 'login') {
      next('/home')
    } else {
      next();
    } 
  } else {
    /**
     * 没有登录时的逻辑
     * 白名单内的路由,直接放行
     * 其它路由跳转到登录页面
     */
    if (whiteList.includes(to.name)) {
      next();
    } else {
      next('/login');
    }  
  } 
}); 
export default router;
